package com.coderman.component.kv.scence;


import com.alibaba.fastjson.JSON;
import com.coderman.component.kv.dataobject.KVPairDO;
import com.coderman.component.kv.mapper.KVMapper;
import com.coderman.component.kv.model.KVPairBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Description:
 * date: 2022/1/11
 *
 * @author fanchunshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service
public class KVJSONService {
    @Autowired
    public KVMapper kvMapper;

    /**
     * 从valueJson获取对象
     * @param key
     * @param clazz
     * @return
     */
    public Object getJsonObject(String key,Class<?> clazz){
        KVPairDO kvPairDO = kvMapper.selectOne(KVPairBO.instance(key,null).convertToDO());
        return JSON.parseObject(kvPairDO.getValueJson(),clazz);
    }


    /**
     * 获取单条KV对象
     * @param kvPairBO
     * @return
     */
    public KVPairBO getOne(KVPairBO kvPairBO){
        KVPairDO kvPairDO = kvMapper.selectOne(kvPairBO.convertToDO());
        return KVPairBO.convertFromDO(kvPairDO);
    }

    /**
     * 判断是否存在
     * @param kvPairBO
     * @return
     */
    public boolean contains(KVPairBO kvPairBO){
        int count = kvMapper.count(kvPairBO.convertToDO());
        return count == 0;
    }

}
